﻿using System;
using System.Web.UI;

namespace MvcImproved.Generic.Controls
{
	public class Literal<TDataItem, TMemberValue> : GenericControl<TDataItem, TMemberValue>
	{
		public string Format { get; set; }

		public Literal(Func<TDataItem, TMemberValue> valueMember)
			: base(valueMember)
		{ }

		public bool OutputEmpty = false;

		protected override void Render(HtmlTextWriter writer)
		{
			string classValue;
			bool spanWrap = false;
			if (Attributes.TryGetValue("cssclass", out classValue) || Attributes.TryGetValue("class", out classValue))
			{
				writer.AddAttribute(HtmlTextWriterAttribute.Class, classValue);
				writer.RenderBeginTag(HtmlTextWriterTag.Span);

				spanWrap = true;
			}

			base.Render(writer);

			if (!DesignMode)
			{
				TMemberValue memberValue = (DataValue == null) ? default(TMemberValue) : ValueMemberLambda(DataValue);
				if (OutputEmpty || ((memberValue != null) && (!String.IsNullOrEmpty(memberValue.ToString()))))
				{
					if (Format == null)
						writer.Write(memberValue);
					else
						writer.Write(String.Format(Format, memberValue));
				}
			}

			if (spanWrap)
				writer.RenderEndTag();
		}
	}

	// Non-generic version of the control that's used in the actual markup
	[ControlBuilder(typeof(GenericControlBuilder))]
	[GenericControlType(typeof(Literal<,>), MemberValue = "ValueMember", GenericParameters = "ModelType")]
	public class Literal : Literal<object, object>
	{
		public Literal()
			: base(null)
		{ }

		public string ModelType
		{
			get;
			set;
		}
	}
}
